package core

import (
	"dgo/MyProj/PrjConf"
	"dgo/MyProj/PrjHttpUtils"
	"dgo/goutils/utils"
	"fmt"
	"gitee.com/ymofen/supervalue"
)

type ProjSubscriber struct {
	ex     *utils.SubscribeCenter
	plugId string
	conf   *wrapper.SuperValue
}

func (this *ProjSubscriber) SetPlugID(val string) {
	this.plugId = val
}

func (this *ProjSubscriber) ReloadConf(conf *wrapper.SuperValue) error {
	if this.conf == nil {
		this.conf = conf
		utils.Monitor.AddMonitorRec(this.ex.Monitor_Exec, this.ex.Monitor_Exec)
		utils.Monitor.AddMonitorRec(this.ex.Monitor_Push, this.ex.Monitor_Push)
	}
	return nil
}

func (this *ProjSubscriber) GetSubscriber() *utils.SubscribeCenter {
	return this.ex
}

func (this *ProjSubscriber) OnObjectNotify(sender interface{}, notifytype int, data interface{}) (rval interface{}, err error) {
	if notifytype == utils.NOTIFY_TYPE_SETCONF {
		if conf, ok := data.(*wrapper.SuperValue); ok {
			err = this.ReloadConf(conf)
		} else {
			err = fmt.Errorf("非法的JSON配置")
		}
	} else if notifytype == utils.NOTIFY_TYPE_RELEASE {

	}
	return
}

/*
**

	响应HttpStatus请求
*/
func (this *ProjSubscriber) OnHttpStatus(rec *PlgHttpRec) (rval interface{}, errcode int, err error) {
	itype := rec.QryAsInt("type", 0)
	if itype == 1 {
		id := rec.QryAsString("id", "")
		str := this.ex.ChannelStatusString(id)
		rec.RespW.Write([]byte(str))
	} else {
		json := wrapper.NewSVObject()
		json.SetKeyValues("plugid", this.plugId, "uuid", PrjConf.APP_UUID,
			"push", this.ex.Monitor_Push.SpeedIO(), "pop", this.ex.Monitor_Exec.SpeedIO(),
			"status", this.ex.StatusString())
		PrjHttpUtils.JSON2TableRec(rec.RespW, "", json.AsJSONString(false))
	}
	return
}

func CreateProjSubscriberFunc(args ...interface{}) (rval interface{}, err error) {
	obj := &ProjSubscriber{}
	if len(args) > 0 {
		if str, ok := args[0].(string); ok {
			obj.plugId = str
		}
	}
	obj.ex = utils.NewSubscribeCenterASync()
	rval = obj
	return
}
